# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


from typing import *


class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:

        h = {v: i for i, v in enumerate(inorder)}

        def f(r, R, s):
            if s == 0:
                return None

            v = postorder[R]
            node = TreeNode(v)
            i = h[v]
            node.left = f(i - 1, R - r + i - 1, s - r + i - 1)
            node.right = f(r, R - 1, r - i)
            return node

        return f(len(inorder) - 1, len(inorder) - 1, len(inorder))
